﻿using UnityEngine;
using System.Collections;
using UnityEditor;

public class FontMakerWindow : EditorWindow
{
    public Font m_myFont;
    public TextAsset m_data;

    private BMFont mbFont = new BMFont();


    [MenuItem("Tool/FontMaker")]
    static void CreateWindow()
    {
        FontMakerWindow windwo = GetWindow<FontMakerWindow>("生成动态字体");



    }


    void OnGUI()
    {
        GUILayout.Space(20);
        m_myFont = EditorGUILayout.ObjectField(m_myFont, typeof(Font)) as Font;
        GUILayout.Space(20);

        m_data = EditorGUILayout.ObjectField(m_data, typeof(TextAsset)) as TextAsset;
        GUILayout.Space(20);

        if (GUILayout.Button("生成字体"))
        {
            if (m_data == null || m_myFont == null)
            {
                Debug.LogError("m_data  和  m_myFont 不能为空。。。");
                return;
            }

            BMFontReader.Load(mbFont, m_data.name, m_data.bytes);  // 借用NGUI封装的读取类
            CharacterInfo[] characterInfo = new CharacterInfo[mbFont.glyphs.Count];
            for (int i = 0; i < mbFont.glyphs.Count; i++)
            {
                BMGlyph bmInfo = mbFont.glyphs[i];
                CharacterInfo info = new CharacterInfo();
                info.index = bmInfo.index;
                info.uv.x = (float)bmInfo.x / (float)mbFont.texWidth;
                info.uv.y = 1 - (float)bmInfo.y / (float)mbFont.texHeight;
                info.uv.width = (float)bmInfo.width / (float)mbFont.texWidth;
                info.uv.height = -1f * (float)bmInfo.height / (float)mbFont.texHeight;
                info.vert.x = (float)bmInfo.offsetX;
                //info.vert.y = (float)bmInfo.offsetY;  
                info.vert.y = 0f;//自定义字库UV从下往上，所以这里不需要偏移，填0即可。 
                info.vert.width = (float)bmInfo.width;
                info.vert.height = (float)bmInfo.height;
                info.width = (float)bmInfo.advance;
                characterInfo[i] = info;
            }
            m_myFont.characterInfo = characterInfo;
        }
    }
}

